package com.acwer.drools.conf;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.kie.api.KieServices;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.web.context.WebApplicationContext;

import com.acwer.utils.CollectionUtils;

@Configuration
public class KiaSessionConfig {

	@Bean
	public KieServices getKieServices() {
		return KieServices.Factory.get();
	}

	@Bean
	public KieContainer kieContainer() {
		return getKieServices().getKieClasspathContainer();

	}
	
	
	
	/**
	 * 使用statu session,并使用request模式，每次请求新建一个session
	 * @return
	 * @throws IOException
	 */
	@Bean
	@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
	public KieSession kieSession() throws IOException {
		//TODO:使用kmodule进行逻辑上的划分，用于后续其他规则的开发
		KieSession session=kieContainer().newKieSession("ksession-rule");
		//加入两个存入中间结果的全局变量
		session.setGlobal("tmpList", new ArrayList<String>());
		session.insert(new HashMap<String, Object>());
		session.setGlobal("collectionUtils", new CollectionUtils());
		session.getWorkItemManager().registerWorkItemHandler("Log", new LoggingWorkItemHandler());
		return session;
	}
}
